package com.cysyz.mylib.myfilter.impl;

import com.cysyz.mylib.myfilter.FilterEvent;
import com.cysyz.mylib.myfilter.Matcher;
import com.cysyz.mylib.myfilter.MyFilter;

import java.util.Collection;
import java.util.Iterator;

/**
 * 过滤工具类
 * 传入includes和excludes的集合，通过matcher提供的匹配规则，当匹配时触发filterEvent的onMatch方法。
 * 具体规则
 * includes和excludes规则
 *  1.如果只传入了includes，那么当target集合的项目匹配时，触发onMatch。
 *  2.如果只传入excludes，那么当target集合中的项目不匹配时，触发onMatch。
 *  3.如果两个都传入，那么就使用规则1。
 */
public class SimpleMyFilter implements MyFilter {
    private FilterEvent filterEvent;
    private Matcher matcher;
    private Collection includes;
    private Collection excludes;

    /**
     *
     * @param matcher 具体的匹配规则提供者
     * @param filterEvent 当匹配时触发此类的onMatch方法
     * @param includes  要包含的项目的集合
     * @param excludes  要排除的项目的集合
     */
    public SimpleMyFilter(Matcher matcher, FilterEvent filterEvent, Collection includes, Collection excludes) {
        this.filterEvent = filterEvent;
        this.matcher = matcher;
        this.includes = includes;
        this.excludes = excludes;
    }

    public SimpleMyFilter(Matcher matcher,FilterEvent filterEvent, Collection includes) {
        this.filterEvent = filterEvent;
        this.matcher = matcher;
        this.includes = includes;
    }

    @Override
    public void process(Collection targetCollection) {

        for (Iterator iterator = targetCollection.iterator(); iterator.hasNext(); ) {
            Object target = iterator.next();
            if ((includes != null && excludes != null) ||
                    (includes != null && excludes == null)) {
                for (Iterator tIterator = includes.iterator();tIterator.hasNext(); ) {
                    Object include =  tIterator.next();
                    if (matcher.match(target, include)) {
                        filterEvent.onMatch(target);
                    }
                }
            } else if (includes == null && excludes != null) {
                for (Iterator tIterator = excludes.iterator(); tIterator.hasNext(); ) {
                    Object exclude =  tIterator.next();
                    if (!matcher.match(target, exclude)) {
                        filterEvent.onMatch(target);
                    }
                }
            } else {
                filterEvent.onMatch(target);
            }
        }

    }

    public FilterEvent getFilterEvent() {
        return filterEvent;
    }

    public void setFilterEvent(FilterEvent filterEvent) {
        this.filterEvent = filterEvent;
    }
}
